<template>
  <span class="plus-table-title-bar__toolbar__clock">
    <el-tooltip placement="top" content="定时器">
      <el-icon ref="TriggerRef" class="plus-table-title-bar__toolbar__icon" :size="18"><Clock /></el-icon>
    </el-tooltip>
    <el-popover ref="PopoverRef" :virtual-ref="TriggerRef" placement="bottom" trigger="click">
<!--      <div>设置定时任务以刷新列表</div>-->
      <div>刷新间隔</div>
      <div>
        <el-radio-group v-model="step">
          <el-radio
            v-for="item in stepOptions"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </div>
      <div class="text-right">
        <el-button type="primary" size="small" @click="startMission">开启</el-button>
        <el-button type="primary" size="small" @click="stopMission">关闭</el-button>
      </div>
    </el-popover>
  </span>
</template>
<script setup>
import { Clock } from "@element-plus/icons-vue";

const defaultSteps = [
  {
    label: "30s",
    value: 30
  },
  {
    label: '60s',
    value: 60
  },
  {
    label: '2min',
    value: 2 * 60
  },
  {
    label: '5min',
    value: 5 * 60
  }
]
const defaultStep = 30

const TriggerRef = ref()
const PopoverRef = ref()
const missionTimer = ref(null)
const step = ref(defaultStep)
const stepOptions = ref(defaultSteps)

const props = defineProps({
  task: {
    type: [Array, Function],
    default: () => []
  },
  startOnMounted: {
    type: Boolean,
    default: false
  },
  steps: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['start'])

const taskFiltered = computed(() => {
  if (props.task) {
    if (typeof props.task === 'function') {
      return [props.task]
    } else if (Array.isArray(props.task)) {
      return props.task.filter(t => (typeof t === 'function'))
    }
  }
  return []
})

const once = ref(false)

watchEffect(() => {
  if (props.startOnMounted && !once.value) {
    if (props.steps && props.steps.length) {
      stepOptions.value = props.steps
      step.value = stepOptions.value[0]?.value ?? defaultStep
    }
    startMission()
    // 保证在开始的时候只调一次
    once.value = true
  }
})

function clearTimer() {
  clearInterval(missionTimer.value)
  missionTimer.value = null
}

function startMission() {
  clearTimer()
  missionTimer.value = setInterval(() => {
    taskFiltered.value.map(fn => {
      fn()
    })
  }, step.value * 1000)
}

function stopMission() {
  clearTimer()
}

onUnmounted(() => {
  clearTimer()
})

onDeactivated(() => {
  clearTimer()
})
</script>
